<template>
  <view class="exam-submission">
    <!-- 考试详情 -->
    <view class="section">
      <view class="section-header">
        <view class="section-title">{{examinationInfo.title}}</view>
        <view class="section-status">
          <u-tag :text="examinationInfo.statusName" type="warning" size="mini" color="#c4996c" bgColor="#faf3ed"></u-tag>
        </view>
      </view>
      <view class="description">
        {{examinationInfo.refer}}
      </view>
      <view class="course-info" @click="handleTitleClick(examinationInfo.courseId)">
        <view class="flex items-center">
          <image class="img" :src="IMG_URL2+'peop/union.svg'" mode="aspectFill" />
          {{examinationInfo.courseName}}
        </view>
        <view>
          <image class="chevronright" :src="IMG_URL2+'common/chevron-right.svg'"></image>
        </view>
      </view>
    </view>
    <!--  0视频 1音频 -->
    <view class="section" v-if="examinationInfo.category=='0'">
      <view class="section-title">上传视频</view>
      <view class="upload-area">
        <!-- <view class="upload-box" @click="handleUpload">
          <u-icon name="plus" size="40" color="#999"></u-icon>
        </view> -->
        <view class="video-preview" v-if="answerUrl">
          <video :src="answerUrl" class="video"></video>
          <!-- <view class="delete-btn" @click.stop="handleDeleteVideo">
            <u-icon name="close" color="#fff" size="24"></u-icon>
          </view> -->
        </view>
      </view>
    </view>
    <view class="section" v-if="examinationInfo.category=='1'">
      <view class="section-title">上传录音</view>
      <view class="upload-area">
        <!-- <view class="upload-box" @click="handleUploadAudio">
          <u-icon name="plus" size="40" color="#999"></u-icon>
        </view> -->
        <view class="audio-preview" v-if="answerUrl">
          <luchaudio :src="answerUrl" :play.sync="audioPlay" :name="`${examinationInfo.title}答题音频`"></luchaudio>
          <!-- <view class="audio-player">
            <u-icon name="play-right" size="40" color="#c4996c" @click="playAudio"></u-icon>
          </view> -->
          <!-- <view class="delete-btn" @click.stop="handleDeleteAudio">
            <u-icon name="close" color="#fff" size="24"></u-icon>
          </view> -->
        </view>
      </view>
      <!-- <view class="upload-area">
        <view class="audio-box" @click="handleStartRecord" v-if="!isRecording && !answerUrl">
          <u-icon name="mic" size="40" color="#999"></u-icon>
          <text class="audio-tip">点击开始录音</text>
        </view>
        <view class="audio-box recording" v-if="isRecording" @click="handleStopRecord">
          <u-icon name="mic-fill" size="40" color="#c4996c"></u-icon>
          <text class="audio-tip">录音中,点击停止</text>
        </view>
      </view> -->
    </view>
    <!-- 导师审核意见 已通过显示审核意见 -->
    <view class="section" v-if="examinationInfo.status!=0&&examinationInfo.status!=3">
      <view class="section-title">导师审核意见</view>
      <view class="section-status">
          <u-tag :text="examinationInfo.statusName" type="warning" size="mini" color="#c4996c" bgColor="#faf3ed"></u-tag>
      </view>
      <view class="refer">
        <view class="refer-content">
          {{examinationInfo.reason}}
        </view>
      </view>
    </view>
    <!-- 不通过 -->
    <view class="footer" v-if="examinationInfo.status==1">
      <button class="submit-btn" @click="goToNextCourse">重新考试</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { studyApi } from "@/api";
import { BASE_API,IMG_URL2 } from "@/config";

import luchaudio from "./luch-audio.vue";
const answerUrl = ref('')
const audioUrl = ref('')
const isRecording = ref(false)
let examinationId =ref('')
const recorderManager = uni.getRecorderManager()
const innerAudioContext = uni.createInnerAudioContext()
let examinationInfo=ref({
  title:'',
  courseName:'',
  category:'',
  refer:'',
  courseId:''
})

// 0待打分 1不通过 2已通过 3未完成
const statusMap = {
  0: '待打分',
  1: '不通过',
  2: '已通过',
  3: '未完成'
}

const handleTitleClick = () => {
  uni.navigateTo({
    url: `/pages/trainingcenter/coursedetails?courseId=${examinationInfo.value.courseId}&currentPage=1`
  })
}

const handleUpload = () => {
  uni.authorize({
    scope: 'scope.camera',
    success() {
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back',
        success: (res) => {
          answerUrl.value = res.tempFilePath
          const filePath = res.tempFilePath;
          // 将二进制数据上传到服务器
          wx.uploadFile({
            url:  BASE_API + '/bg/file/upload',   // 上传的 URL 地址
            filePath: filePath,   // 文件的临时路径
            name: 'file',   // 服务器端接收文件的字段名
            header: {
              'content-type': 'multipart/form-data'   // 设置请求头
            },
            formData: {},
            success: function(res) {
              // 上传成功后的操作
              console.log(JSON.parse(res.data));
              userInfo.header=JSON.parse(res.data).result.url
            },
            fail: function(res) {
              // 上传失败后的操作
              console.log(res);
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: '选择视频失败',
            icon: 'none'
          })
        }
      })

      
    },
    fail() {
      uni.showModal({
        title: '提示',
        content: '请在设置中允许使用摄像头权限',
        success(res) {
          if (res.confirm) {
            uni.openSetting()
          }
        }
      })
    }
  })
}
const goToNextCourse = ()=>{
  uni.navigateTo({
    url: `/pages/trainingcenter/takethetest?id=${examinationInfo.value.examinationQuestionId}`,
  })
}


const handleDeleteVideo = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该视频吗？',
    success: (res) => {
      if (res.confirm) {
        answerUrl.value = ''
      }
    }
  })
}

const handleStartRecord = () => {
  uni.authorize({
    scope: 'scope.record',
    success() {
      recorderManager.start({
        duration: 60000, // 最长录音时间，单位ms
        format: 'mp3'
      })
      isRecording.value = true
    },
    fail() {
      uni.showModal({
        title: '提示',
        content: '请在设置中允许使用麦克风权限',
        success(res) {
          if (res.confirm) {
            uni.openSetting()
          }
        }
      })
    }
  })
}

const handleStopRecord = () => {
  recorderManager.stop()
  isRecording.value = false
}

recorderManager.onStop((res) => {
  audioUrl.value = res.tempFilePath
})

const playAudio = () => {
  innerAudioContext.src = audioUrl.value
  innerAudioContext.onPlay(() => {
    console.log('开始播放');
  });
}

const handleDeleteAudio = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该录音吗？',
    success: (res) => {
      if (res.confirm) {
        audioUrl.value = ''
      }
    }
  })
}

const getData=()=>{
  let params={
    id: examinationId.value
  }
  studyApi.STUDYGETEXAMINATIONBYID(params).then(res => {
    if(res.code == 200) {
      examinationInfo.value = {
        ...res.result,
        
        // statusText: res.result.status != null && res.result.status !== undefined ? statusMap[res.result.status] : '未知状态'
      }
      answerUrl.value= examinationInfo.value.answerUrl
    } else {
      uni.showToast({ title: res.errMsg, icon: "none" });
    }
  })
}

onLoad((options) => {
  if (options.id) {
    examinationId.value = options.id
    getData()
  }
  
})
onShow(async () => {
  if(examinationId.value){
    getData()
  }
});
</script>

<style lang="scss" scoped>
.exam-submission {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;

  .section {
    background-color: #fff;
    padding: 30rpx;
    box-sizing: border-box;
    margin-bottom: 20rpx;

    .section-header {
      margin-bottom: 20rpx;
      gap: 20rpx;
    }

    .section-title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 20rpx;
    }
    .section-status{
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
    }

    .description {
      font-size: 28rpx;
      color: #666;
      line-height: 1.5;
      margin-bottom: 20rpx;
    }
    .course-info{
      display: flex;
      align-items: center;
      justify-content: space-between;
      .img {
        width: 28rpx;
        height: 28rpx;
        margin-right: 10rpx;
      }
      .chevronright {
        width: 32rpx;
        height: 32rpx;
      }
    }

    .upload-area {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
      margin-bottom: 20rpx;

      .upload-box, .audio-box {
        width: 200rpx;
        height: 200rpx;
        background-color: #f5f5f5;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border-radius: 12rpx;

        &:active {
          opacity: 0.8;
        }

        &.recording {
          background-color: #faf3ed;
        }

        .audio-tip {
          font-size: 24rpx;
          color: #999;
          margin-top: 10rpx;
        }
      }

      .video-preview, .audio-preview {
        position: relative;
        width: 100%;
        
        border-radius: 12rpx;
        overflow: hidden;

        .video {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        

        .audio-player {
          width: 100%;
          height: 100%;
          background-color: #f5f5f5;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .delete-btn {
          position: absolute;
          top: 10rpx;
          right: 10rpx;
          width: 40rpx;
          height: 40rpx;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .video-preview{
          height: 220px;
        }
    }
  }
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx;
    box-sizing: border-box;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .submit-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #c4996c;
      color: #fff;
      border: none;
      border-radius: 44rpx;
      font-size: 32rpx;

      &:active {
        opacity: 0.9;
      }
    }
  }
}
</style>